<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" size="small">
      <el-form-item label="全宗名称" prop="fondsName">
        <el-input v-model="queryParams.fondsName" placeholder="请输入全宗名称" clearable style="width: 240px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <!--部门数据-->
      <!-- <el-col :span="4" :xs="24">
          <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入名称" clearable  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                  :filter-node-method="filterNode" :default-expanded-keys="expandedkeys"
                  :current-node-key="currentNodekey" ref="tree" node-key="id" default-expand-all highlight-current
                  @node-click="handleNodeClick" />
          </div>
      </el-col> -->
      <!--用户数据-->
      <!-- v-hasPermi="['system:user:add']" -->

      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8" ref="refbut">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">添加</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :search="false"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="generalList" :height="tableHeight" border>
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="序号" sortable align="center" type="index"/>
          <el-table-column label="全宗名称" align="center" key="fondsName" prop="fondsName"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="全宗号" align="center" key="fondsCode" prop="fondsCode"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                         @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button type="text" icon="el-icon-edit"
                         @click="handleUpdate(scope.row)">修改
              </el-button>
              <el-button type="text" icon="el-icon-delete"
                         @click="handleDelete(scope.row)">删除
              </el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" style="margin-top:8%" append-to-body>
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="全宗名称：" prop="fondsName">
          <el-input v-model="form.fondsName" placeholder="请输入全宗名称"/>
        </el-form-item>

        <el-form-item label="全宗号：" prop="fondsCode">
          <el-input v-model="form.fondsCode" :disabled="qzhIsDisabled" placeholder="请输入全宗号"
                    onKeyUp="value=value.replace(/[\W]/g,'')"
                    @blur="salaryChange"/>
        </el-form-item>
        <el-form-item label="立档单位：" prop="deptId">
          <treeselect v-model="form.deptId" :options="optionSelect" :normalizer="normalizer"  :show-count="true" placeholder="请选择归属部门"
                      style="width:100%"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTenantTree,
  listFONDS,
  addFONDS,
  updateFONDS,
  getFONDS,
  delFONDS
} from "@/api/archive/application/generalManager.js"
import estimateTableHeight from '@/mixins/estimateTableHeight'//vue项目中element-tabel自动计算高度
import { deptTreeSelect,deptTreeNoDateScope } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  mixins: [estimateTableHeight], // 混入方法
  components: {Treeselect},
  data() {
    return {
      optionSelect: [], //部门
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 立档单位表格数据
      generalList: null,
      // 弹出层标题
      title: "",
      //立档单位信息树lieb
      deptOptions: undefined,
      //全宗号：添加可以编辑，修改时禁止编辑
      qzhIsDisabled: false,
      //默认展开的树节点
      expandedkeys: [],
      //默认选中的树节点
      currentNodekey: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fondsName: undefined,
      },

      // 表单校验
      rules: {
        fondsName: [
          {required: true, message: "请输入全宗名称", trigger: "blur"},
        ],
        fondsCode: [
          {required: true, message: "请输入全宗号", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: '请选择立档单位', trigger: 'change'}
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getDeptTree();
    this.getList();
    this.deptTreeSelectPost();
  },
  methods: {

    normalizer(node) {
                if (node.children == null || node.children == undefined||!node.children.length) {
                  delete node.children;
                  }
            return node
        },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //解决vue+element— el-input 限制只能输入数字时和字母时与表单验证rules冲突问题
    salaryChange(e) {
      this.form.fondsCode = e.target.value;
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listFONDS(this.queryParams).then(response => {
          this.generalList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.fondsName + '"吗？').then(() => {

        this.form = row;
        updateFONDS(this.form).then(response => {
          this.$modal.msgSuccess(text + "成功");
          this.reset();
          this.getList();
        })

      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 查询立档单位树结构 */
    // getDeptTree() {
    //     listTenantTree().then(response => {
    //         this.deptOptions = response.data;
    //         if (this.deptOptions.length > 0) {
    //             this.currentNodeKey = this.deptOptions[0].children[0].id;
    //             this.expandedkeys.push(this.deptOptions[0].children[0].id);
    //             console.log(this.expandedkeys, this.currentNodeKey)
    //             this.$nextTick(() => {
    //                 this.$refs.tree.setCurrentKey(this.deptOptions[0].children[0].id)
    //             })
    //             this.queryParams.tenantCode = response.data[0].children[0].tenantCode;
    //             this.getList();
    //         }


    //     });
    // },
    //部门（单选）
    deptTreeSelectPost() {
      // deptTreeSelect().then(response => {
      //   this.optionSelect = response.data;
      // })

      deptTreeNoDateScope().then(response => {
                this.optionSelect = response.data;
            })
    },
    // 表单重置
    reset() {
      this.form = {
        fondsName: null,
        fondsCode: null,
        tenantCode: this.queryParams.tenantCode
      };

      this.$refs["ruleForm"].resetFields();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.tenantCode = data.tenantCode;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();

    },

    /** 新增按钮操作 */
    handleAdd() {
      this.form={};
      this.qzhIsDisabled = false;
      this.open = true;
      this.title = "添加立档单位全宗";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.qzhIsDisabled = true;
      //this.reset();
      const ID = row.id || this.ids;
      getFONDS(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改立档单位全宗";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form, "lsdjfkl")
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFONDS(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            this.form.status = 0;
            addFONDS(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ID = row.id || this.ids;
      this.$modal.confirm('是否确认删除全宗名称为"' + row.fondsName + '"的数据项？').then(function () {
        return delFONDS(ID);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

  }
}
</script>
<style scoped>
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>

